package com.cy.detectsys.util;

import cn.hutool.core.io.FileUtil;
import com.cy.detectsys.config.CustomException;
import org.apache.commons.codec.binary.Base64;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

import javax.crypto.BadPaddingException;
import javax.crypto.Cipher;
import javax.crypto.IllegalBlockSizeException;
import javax.crypto.spec.IvParameterSpec;
import javax.crypto.spec.SecretKeySpec;
import javax.imageio.stream.FileImageOutputStream;
import java.io.UnsupportedEncodingException;
import java.security.*;
import java.security.interfaces.RSAPrivateKey;
import java.security.interfaces.RSAPublicKey;
import java.security.spec.PKCS8EncodedKeySpec;
import java.security.spec.X509EncodedKeySpec;
import java.util.Arrays;
import java.util.HashMap;
import java.util.Map;

import cn.hutool.core.util.HexUtil;
import cn.hutool.crypto.SecureUtil;
import cn.hutool.crypto.asymmetric.KeyType;
import cn.hutool.crypto.asymmetric.RSA;

import java.io.*;
import java.security.KeyPair;

import static com.cy.detectsys.constant.RSAKeyConstant.privateKey;


public class RSAUtils {

    private static final Logger log = LoggerFactory.getLogger(RSAUtils.class);

    private static final String PUBLIC_KEY = "publicKey";
    private static final String PRIVATE_KEY = "privateKey";

    public static HashMap getAesMap(File probdeData) {
        HashMap<String, byte[]> map = new HashMap<>();
        byte[] aes_iv = null;
        byte[] aes_key = null;
        try {
            for (File file : probdeData.listFiles()) {
                if (file.getName().contains("iv")) {
                    aes_iv = privateKeyDecrypt(file);
                    map.put("aes_iv", aes_iv);
                }

                if (file.getName().contains("key")) {
                    aes_key = privateKeyDecrypt(file);
                    map.put("aes_key", aes_key);
                }
            }
        } catch (Exception e) {

            throw new CustomException("获取AES解密信息异常");
        }


        return map;

    }


    public static String aesDecrypt(byte[] sstr, byte[] skey, byte[] siv) {
        try {
            if (skey == null) {
                log.info("key is null");
                return null;
            }

            SecretKeySpec keySpec = new SecretKeySpec(skey, "AES");
            Cipher cipher = Cipher.getInstance("AES/CBC/PKCS5Padding");//算法/模式/补码方式
            IvParameterSpec iv = new IvParameterSpec(siv);   //使用CBC模式，需要一个向量iv，可增加加密算法的强度
            cipher.init(Cipher.DECRYPT_MODE, keySpec, iv);

            byte[] origin = cipher.doFinal(sstr);
            String str = new String(origin);
            return str;

        } catch (Exception e) {
            throw new CustomException(e.getMessage());
        }

    }

    public static String[] initRSA() {


        KeyPair rsa = SecureUtil.generateKeyPair("RSA", 2048);
        String privateKey = cn.hutool.core.codec.Base64.encode(rsa.getPrivate().getEncoded());
        String publicKey = cn.hutool.core.codec.Base64.encode(rsa.getPublic().getEncoded());
        String keyword[] = {privateKey, publicKey};
        return keyword;
    }

    public static void main(String[] args) {
        String[] strings = initRSA();
        //测试采用单独一个文件
        // File file = new File("C:\\Users\\W\\Documents\\WeChat Files\\wxid_dd2l39sslfud22\\FileStorage\\File\\新建文件夹\\新建文件夹\\新建文本文档.txt");
        // EncodeFile(file, strings);
        // System.out.println("文件加密成功");
        // DecodeFile(file, strings);
        String path = "C:\\Users\\W\\Documents\\WeChat Files\\wxid_dd2l39sslfud22\\FileStorage\\File\\新建文件夹";
        //  多级遍历子文件对文件进行处理
        RecursiveEncode(path, strings);
        RecursiveDecode(path, strings);
    }

    private static void RecursiveDecode(String path, String[] strings) {
        File folder = new File(path);
        //查看地址的文件是否存在
        if (!folder.exists()) {
            return;
        }
        if (!folder.isDirectory()) {
            //如果当前file不是文件夹，则直接进行加密
            DecodeFile(folder, strings);
        } else {
            //如果当前file是目录
            File[] files = folder.listFiles();
            if (files != null && files.length > 0) {
                for (File file : files) {
                    if (file.isDirectory()) {
                        RecursiveDecode(file.getAbsolutePath(), strings);
                    } else {
                        DecodeFile(file, strings);
                    }
                }
            }
        }
    }

    private static void RecursiveEncode(String path, String[] strings) {
        File folder = new File(path);
        //查看地址的文件是否存在
        if (!folder.exists()) {
            return;
        }
        if (!folder.isDirectory()) {
            //如果当前file不是文件夹，则直接进行加密
            EncodeFile(folder, strings);
        } else {
            //如果当前file是目录
            File[] files = folder.listFiles();
            if (files != null && files.length > 0) {
                for (File file : files) {
                    if (file.isDirectory()) {
                        RecursiveEncode(file.getAbsolutePath(), strings);
                    } else {
                        EncodeFile(file, strings);
                    }
                }
            }
        }
    }

    //单个文档非堆成加密
    public static void EncodeFile(File file, String[] keyword) {
        //封装 文件读取加密并替换原文档
        String text = FileToString(file);

        String Encodetext = dataEncrypt(text, keyword);
        // System.out.println(加密信息);
        RewriteFile(file, Encodetext);
    }

    //单个文档非堆成解密
    private static void DecodeFile(File file, String[] keyword) {
        //封装 文件读取解密并替换原文档
        String text = FileToString(file);
        String Decodetext = dataDecrypt(text, keyword);
        // System.out.println(Decodetext);
        RewriteFile(file, Decodetext);

    }

    //强制读取文件内容，但可能会破坏文件格式
    public static String FileToString(File file) {
        try {
            FileInputStream fis = new FileInputStream(file);
            InputStreamReader isr = new InputStreamReader(fis, "UTF-8");
            StringBuilder stringBuilder = new StringBuilder();

            BufferedReader br = new BufferedReader(isr);

            String str_line = "";
            //逐行读取文本
            while ((str_line = br.readLine()) != null) {
                stringBuilder.append(str_line + "\n");
            }
            String fileTextString = stringBuilder.toString();
            fis.close();
            isr.close();
            br.close();

            return fileTextString;
        } catch (IOException e) {
            e.printStackTrace();
            return null;
        }
    }

    //强制清除文件内容，并填入新的文本
    public static void RewriteFile(File file, String msgEncrypt) {

        try {
            if (!file.exists()) {
                file.createNewFile();
            }
            //在重新文件之前需要清空源数据
            FileWriter fileWriter = new FileWriter(file);
            fileWriter.write("");
            fileWriter.flush();
            fileWriter.close();
            //重新写入
            FileOutputStream fileOutputStream = new FileOutputStream(file);
            if (msgEncrypt != null) {
                byte[] bytes = msgEncrypt.getBytes();
                fileOutputStream.write(bytes);
                fileOutputStream.flush();
                fileOutputStream.close();
            }

        } catch (IOException e) {
            throw new RuntimeException(e);
        }

    }

    //真正数据加密
    public static String dataEncrypt(String msg, String[] keyword) {
        //根据公钥私钥生成RSA对象
        RSA rsa = new RSA(keyword[0], keyword[1]);
        //使用公钥进行加密，返回加密后的字符串
        String msgEncrypt = rsa.encryptBcd(msg, KeyType.PublicKey);
        return msgEncrypt;
    }

    //真正数据解密
    public static String dataDecrypt(String msgEncrypt, String[] keyword) {
        //根据公钥私钥生成RSA对象
        RSA rsa = new RSA(keyword[0], keyword[1]);
        //使用私钥进行解密，并返回解密文本
        byte[] decrypt = rsa.decrypt(HexUtil.decodeHex(msgEncrypt), KeyType.PrivateKey);
        // return StrUtil.str(decrypt, CharsetUtil.CHARSET_UTF_8);
        return new String(decrypt);

    }

    /**
     * 功能描述:
     * 〈随机生成密钥对〉
     *
     * @return : java.util.Map<java.lang.String,java.lang.String>
     * @author gggcgba 【wechat:13031016567】
     * @date : 2021/5/17 0017 17:38
     */
    public static Map<String, String> genKeyPair() throws NoSuchAlgorithmException {
        System.out.println("开始生成公钥私钥对");
        // KeyPairGenerator类用于生成公钥和私钥对，基于RSA算法生成对象
        KeyPairGenerator keyPairGen = KeyPairGenerator.getInstance("RSA");
        // 初始化密钥对生成器，密钥大小为96-1024位
        keyPairGen.initialize(1024, new SecureRandom());
        // 生成一个密钥对，保存在keyPair中
        KeyPair keyPair = keyPairGen.generateKeyPair();
        RSAPrivateKey privateKey = (RSAPrivateKey) keyPair.getPrivate();    // 得到私钥
        RSAPublicKey publicKey = (RSAPublicKey) keyPair.getPublic();        // 得到公钥
        String publicKeyString = new String(Base64.encodeBase64(publicKey.getEncoded()));
        // 得到私钥字符串
        String privateKeyString = new String(Base64.encodeBase64((privateKey.getEncoded())));
        // 将公钥和私钥保存到Map
        Map<String, String> map = new HashMap<>();
        map.put(PUBLIC_KEY, publicKeyString);
        map.put(PRIVATE_KEY, privateKeyString);
        return map;
    }


    /**
     * RSA私钥加密
     *
     * @param str
     * @param privateKey
     * @return
     * @throws Exception
     * @author gggcgba 【wechat:13031016567】
     */
    public static String privateKeyEncrypt(String str, String privateKey) throws Exception {
        log.info("{}|RSA私钥加密前的数据|str:{}|publicKey:{}", str);
        //base64编码的公钥
        byte[] decoded = Base64.decodeBase64(privateKey);
        PrivateKey priKey = KeyFactory.getInstance("RSA").
                generatePrivate(new PKCS8EncodedKeySpec(decoded));
        //RSA加密
        Cipher cipher = Cipher.getInstance("RSA");
        cipher.init(Cipher.ENCRYPT_MODE, priKey);

        //当长度过长的时候，需要分割后加密 117个字节
        byte[] resultBytes = getMaxResultEncrypt(str, cipher);

        String outStr = Base64.encodeBase64String(resultBytes);
        log.info("{}|RSA私钥加密后的数据|outStr:{}", outStr);
        return outStr;
    }

    /**
     * RSA公钥解密
     *
     * @param str
     * @param publicKey
     * @return
     * @throws Exception
     * @author gggcgba 【wechat:13031016567】
     */
    public static String publicKeyDecrypt(String str, String publicKey) throws Exception {
        log.info("{}|RSA公钥解密前的数据|str:{}|publicKey:{}", str);
        //64位解码加密后的字符串
        byte[] inputByte = Base64.decodeBase64(str.getBytes("UTF-8"));
        //base64编码的私钥
        byte[] decoded = Base64.decodeBase64(publicKey);
        PublicKey pubKey = KeyFactory.getInstance("RSA")
                .generatePublic(new X509EncodedKeySpec(decoded));
        //RSA解密
        Cipher cipher = Cipher.getInstance("RSA");
        cipher.init(Cipher.DECRYPT_MODE, pubKey);
        //当长度过长的时候，需要分割后解密 128个字节
        String outStr = new String(getMaxResultDecrypt(str, cipher));
        log.info("{}|RSA公钥解密后的数据|outStr:{}", outStr);
        return outStr;
    }


    /**
     * RSA公钥加密
     *
     * @param str       加密字符串
     * @param publicKey 公钥
     * @return 密文
     * @throws Exception 加密过程中的异常信息
     * @author gggcgba 【wechat:13031016567】
     */
    public static String publicKeyEncrypt(String str, String publicKey) throws Exception {
        log.info("{}|RSA公钥加密前的数据|str:{}|publicKey:{}", str);
        //base64编码的公钥
        byte[] decoded = Base64.decodeBase64(publicKey);
        RSAPublicKey pubKey = (RSAPublicKey) KeyFactory.getInstance("RSA").
                generatePublic(new X509EncodedKeySpec(decoded));
        //RSA加密
        Cipher cipher = Cipher.getInstance("RSA");
        cipher.init(Cipher.ENCRYPT_MODE, pubKey);

        //当长度过长的时候，需要分割后加密 117个字节
        byte[] resultBytes = getMaxResultEncrypt(str, cipher);

        String outStr = Base64.encodeBase64String(resultBytes);
        log.info("{}|公钥加密后的数据|outStr:{}", outStr);
        return outStr;
    }

    private static byte[] getMaxResultEncrypt(String str, Cipher cipher) throws IllegalBlockSizeException, BadPaddingException {
        byte[] inputArray = str.getBytes();
        int inputLength = inputArray.length;
        log.info("{}|加密字节数|inputLength:{}", inputLength);
        // 最大加密字节数，超出最大字节数需要分组加密
        int MAX_ENCRYPT_BLOCK = 117;
        // 标识
        int offSet = 0;
        byte[] resultBytes = {};
        byte[] cache = {};
        while (inputLength - offSet > 0) {
            if (inputLength - offSet > MAX_ENCRYPT_BLOCK) {
                cache = cipher.doFinal(inputArray, offSet, MAX_ENCRYPT_BLOCK);
                offSet += MAX_ENCRYPT_BLOCK;
            } else {
                cache = cipher.doFinal(inputArray, offSet, inputLength - offSet);
                offSet = inputLength;
            }
            resultBytes = Arrays.copyOf(resultBytes, resultBytes.length + cache.length);
            System.arraycopy(cache, 0, resultBytes, resultBytes.length - cache.length, cache.length);
        }
        return resultBytes;
    }

    /**
     * RSA私钥解密
     *
     * @param str        加密字符串
     * @param privateKey 私钥
     * @return 铭文
     * @throws Exception 解密过程中的异常信息
     * @author gggcgba 【wechat:13031016567】
     */
    public static String privateKeyDecrypt(String str, String privateKey) throws Exception {
        //64位解码加密后的字符串

        byte[] inputByte = Base64.decodeBase64(str.getBytes("UTF-8"));
        //base64编码的私钥
        byte[] decoded = Base64.decodeBase64(privateKey);
        RSAPrivateKey priKey = (RSAPrivateKey) KeyFactory.getInstance("RSA")
                .generatePrivate(new PKCS8EncodedKeySpec(decoded));
        //RSA解密
        Cipher cipher = Cipher.getInstance("RSA");
        cipher.init(Cipher.DECRYPT_MODE, priKey);
        //byte[] bytes = cipher.doFinal(inputByte);

        String outStr = new String(cipher.doFinal(inputByte));
        return outStr;
    }

    public static byte[] privateKeyDecrypt(byte[] inputByte, String privateKey) throws Exception {
        //base64编码的私钥
        byte[] decoded = Base64.decodeBase64(privateKey);
        RSAPrivateKey priKey = (RSAPrivateKey) KeyFactory.getInstance("RSA")
                .generatePrivate(new PKCS8EncodedKeySpec(decoded));
        //RSA解密
        Cipher cipher = Cipher.getInstance("RSA");
        cipher.init(Cipher.DECRYPT_MODE, priKey);
        byte[] bytes = cipher.doFinal(inputByte);
        return bytes;
    }


    public static byte[] privateKeyDecrypt(File file) throws Exception {
        byte[] inputByte = FileUtil.readBytes(file.getAbsolutePath());

        //base64编码的私钥
        byte[] decoded = Base64.decodeBase64(privateKey);
        RSAPrivateKey priKey = (RSAPrivateKey) KeyFactory.getInstance("RSA")
                .generatePrivate(new PKCS8EncodedKeySpec(decoded));
        //RSA解密
        Cipher cipher = Cipher.getInstance("RSA");
        cipher.init(Cipher.DECRYPT_MODE, priKey);
        byte[] bytes = cipher.doFinal(inputByte);
        return bytes;
    }

    /**
     * 使用私钥对RSA加密图片进行解密并生成PNG图片
     *
     * @param str
     * @param privateKey
     * @return
     * @throws Exception
     */
    public static void privateKeyDecryptPNG(String str, String privateKey, String path) throws Exception {
        //64位解码加密后的字符串
        //base64编码的私钥
        byte[] decoded = Base64.decodeBase64(privateKey);
        RSAPrivateKey priKey = (RSAPrivateKey) KeyFactory.getInstance("RSA")
                .generatePrivate(new PKCS8EncodedKeySpec(decoded));
        //RSA解密
        Cipher cipher = Cipher.getInstance("RSA");
        cipher.init(Cipher.DECRYPT_MODE, priKey);
//        String outStr = new String(cipher.doFinal(inputByte));
        //当长度过长的时候，需要分割后解密 128个字节
        try {

            byte[] inputArray = Base64.decodeBase64(str.getBytes("UTF-8"));
            int inputLength = inputArray.length;
            log.info("解密字节数:{}", inputLength);
            // 最大解密字节数，超出最大字节数需要分组加密
            int MAX_ENCRYPT_BLOCK = 256;
            // 标识
            int offSet = 0;
            byte[] resultBytes = {};
            byte[] cache = {};
            //数据解密
            while (inputLength - offSet > 0) {
                if (inputLength - offSet > MAX_ENCRYPT_BLOCK) {
                    cache = cipher.doFinal(inputArray, offSet, MAX_ENCRYPT_BLOCK);
                    offSet += MAX_ENCRYPT_BLOCK;
                } else {
                    cache = cipher.doFinal(inputArray, offSet, inputLength - offSet);
                    offSet = inputLength;
                }
                resultBytes = Arrays.copyOf(resultBytes, resultBytes.length + cache.length);
                System.arraycopy(cache, 0, resultBytes, resultBytes.length - cache.length, cache.length);
            }
            //数据解密得到byte[]数组
            try {
                FileImageOutputStream imageOutputStream = new FileImageOutputStream(new File(path));
                imageOutputStream.write(resultBytes, 0, resultBytes.length);
                imageOutputStream.close();
                System.out.println("图片解密地址：" + path);
            } catch (Exception e) {
                System.out.println(e.getMessage());
            }
        } catch (Exception e) {
        }
    }

    private static byte[] getMaxResultDecrypt(String str, Cipher cipher) throws IllegalBlockSizeException, BadPaddingException, UnsupportedEncodingException {
        byte[] inputArray = Base64.decodeBase64(str.getBytes("UTF-8"));
        int inputLength = inputArray.length;
        log.info("解密字节数:{}", inputLength);
        // 最大解密字节数，超出最大字节数需要分组加密
        int MAX_ENCRYPT_BLOCK = 256;
        // 标识
        int offSet = 0;
        byte[] resultBytes = {};
        byte[] cache = {};
        while (inputLength - offSet > 0) {
            if (inputLength - offSet > MAX_ENCRYPT_BLOCK) {
                cache = cipher.doFinal(inputArray, offSet, MAX_ENCRYPT_BLOCK);
                offSet += MAX_ENCRYPT_BLOCK;
            } else {
                cache = cipher.doFinal(inputArray, offSet, inputLength - offSet);
                offSet = inputLength;
            }
            resultBytes = Arrays.copyOf(resultBytes, resultBytes.length + cache.length);
            System.arraycopy(cache, 0, resultBytes, resultBytes.length - cache.length, cache.length);
        }
        return resultBytes;
    }

}
